
from dvadmin.lowcode.models import Block
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet
from dvadmin.utils.json_response import SuccessResponse, ErrorResponse, DetailResponse
from rest_framework.decorators import action
from django.db.models import Q

class BLockSerializer(CustomModelSerializer):
    """
    区块-序列化器
    """
    class Meta:
        model = Block
        fields = "__all__"
        # read_only_fields = ["id"]

class BLockViewSet(CustomModelViewSet):
    """
    区块管理
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = Block.objects.all()
    serializer_class = BLockSerializer
    extra_filter_backends = []
    # permission_classes = []
    filter_fields = {
        "name": ["icontains"],
        "id":["exact"],
        "blockTypeId": ["exact"]
    }

    @action(methods=['GET'], detail=False, permission_classes=[])
    def search(self, request, *args, **kwargs):
        data =request.query_params
        print(data)
        con = Q()
        id = data.get('blockTypeId',None)
        limit = data.get('limit',None)
        name = data.get('name',None)
        if id:
            q1 = Q()
            q1.connector = 'OR'
            q1.children.append(('blockTypeId', id))
            q1.children.append(('blockTypeId__pid', id))
            con.add(q1, 'AND')
        if name:
            con.add(Q(name=name), 'AND')
        obj = self.queryset.filter(con)
        serializer = self.get_serializer(obj, many=True, request=request)
        return SuccessResponse(data=serializer.data, msg="获取成功")

